/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.user.dao;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.common.dao.BaseDAO;
import etcore.webapp.grouptalk.common.dao.HibernateSessionFactory;
import etcore.webapp.grouptalk.common.dao.MessageDAO;
import etcore.webapp.grouptalk.common.object.Message;
import etcore.webapp.grouptalk.user.object.Focus;
import etcore.webapp.grouptalk.user.object.Member;
import etcore.webapp.grouptalk.user.object.User;

/**
 * An instance of UserDAO is a data access object used to access User, which
 * contains query and update operations
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class UserDAO extends BaseDAO {

	@Override
	public void deleteSingle(Object persistentInstance) {
		Session session = HibernateSessionFactory.getSession();
		if (persistentInstance instanceof User) {
			User user = (User) persistentInstance;
			MessageDAO messageDAO = new MessageDAO();
			long all = messageDAO.findAllSizeByProperty(PageConstants.USERNAME,
					user.getUserName());
			@SuppressWarnings("unchecked")
			List<Integer> messageIDs = (List<Integer>) messageDAO
					.findIDsByProperty(PageConstants.USERNAME,
							user.getUserName(), 0, (int) all);
			if (messageIDs != null)
				for (Integer id : messageIDs) {
					Message message = messageDAO.findById(id);
					messageDAO.deleteSingle(message);
				}
			MemberDAO memberDAO = new MemberDAO();
			List<Member> members = memberDAO.findByProperty(
					PageConstants.USERNAME, user.getUserName());
			if (members != null)
				memberDAO.deleteList(members);

			FocusDAO focusDAO = new FocusDAO();
			List<Focus> focuses = focusDAO.findByProperty(
					"fromUser", user.getUserName());
			if (focuses != null)
				focusDAO.deleteList(focuses);
			
			List<Focus> focuses2 = focusDAO.findByProperty(
					"toUser", user.getUserName());
			if (focuses2 != null)
				focusDAO.deleteList(focuses2);

		}

		session.delete(persistentInstance);

	}

	public List<User> findAll() {
		Session session = HibernateSessionFactory.getSession();
		String queryString = "from User";
		Query queryObject = session.createQuery(queryString);
		@SuppressWarnings("unchecked")
		List<User> results = queryObject.list();

		return results;

	}

	public List<User> findAll(int begin, int length) {
		Session session = HibernateSessionFactory.getSession();
		String queryString = "from User order by regTime desc ";
		Query queryObject = session.createQuery(queryString);
		queryObject.setFirstResult(begin);
		queryObject.setMaxResults(length);
		@SuppressWarnings("unchecked")
		List<User> results = queryObject.list();

		return results;

	}

	public List<User> findUsers(int begin, int length) {
		Session session = HibernateSessionFactory.getSession();
		String queryString = "from User where isLock<>-1 and  STRCMP(now(),regTime)>=0 order by regTime desc ";
		Query queryObject = session.createQuery(queryString);
		queryObject.setFirstResult(begin);
		queryObject.setMaxResults(length);
		@SuppressWarnings("unchecked")
		List<User> results = queryObject.list();

		return results;

	}

	public List<User> findAllBySort(int begin, int length, String sort) {
		Session session = HibernateSessionFactory.getSession();
		String queryString = "from User  order by " + sort + " desc ";
		Query queryObject = session.createQuery(queryString);
		queryObject.setFirstResult(begin);
		queryObject.setMaxResults(length);
		@SuppressWarnings("unchecked")
		List<User> results = queryObject.list();

		return results;

	}

	public long findSizeByFutureDays(String inputDate, Integer days) {

		Session session = HibernateSessionFactory.getSession();
		String queryString = "select count(gt_user.id) as ct from gt_user where   (TO_DAYS('"
				+ inputDate
				+ "')-TO_DAYS(gt_user.regTime))=?  and gt_user.isLock<>-1";

		SQLQuery sqlQuery = session.createSQLQuery(queryString).addScalar("ct",
				Hibernate.INTEGER);
		sqlQuery.setParameter(0, days);
		// queryObject.setParameter(0, g);
		@SuppressWarnings("rawtypes")
		List results = sqlQuery.list();

		return (results == null || results.size() == 0) ? 0 : ((Number) results
				.get(0)).longValue();

	}

	public long findSizeByFutureDays(Integer days) {

		Session session = HibernateSessionFactory.getSession();
		String queryString = "select count(gt_user.id) as ct from gt_user where   (TO_DAYS(now())-TO_DAYS(gt_user.regTime))=?  and gt_user.isLock<>-1";

		SQLQuery sqlQuery = session.createSQLQuery(queryString).addScalar("ct",
				Hibernate.INTEGER);
		sqlQuery.setParameter(0, days);
		// queryObject.setParameter(0, g);
		@SuppressWarnings("rawtypes")
		List results = sqlQuery.list();

		return (results == null || results.size() == 0) ? 0 : ((Number) results
				.get(0)).longValue();

	}

	public long findSize() {
		Session session = HibernateSessionFactory.getSession();

		String queryString = "select count(*) from User where isLock<>-1 and STRCMP(now(),regTime)>=0";
		Query queryObject = session.createQuery(queryString);
		Object results = queryObject.uniqueResult();

		return (results == null) ? 0 : ((Number) results).longValue();

	}

	public long findAllSize() {
		Session session = HibernateSessionFactory.getSession();

		String queryString = "select count(*) from User";
		Query queryObject = session.createQuery(queryString);
		Object results = queryObject.uniqueResult();

		return (results == null) ? 0 : ((Number) results).longValue();

	}

	public User findById(java.lang.Integer id) {
		Session session = HibernateSessionFactory.getSession();
		User instance = (User) session.get(User.class.getName(), id);

		return instance;

	}

	public User findById(java.lang.Integer id, boolean clear) {
		Session session = HibernateSessionFactory.getSession();
		if (clear)
			session.clear();
		User instance = (User) session.get(User.class.getName(), id);

		return instance;

	}

	public List<User> findByProperty(String propertyName, Object value) {
		Session session = HibernateSessionFactory.getSession();
		String queryString = "from User as model where model." + propertyName
				+ "= ? order by id desc";
		Query queryObject = session.createQuery(queryString);
		queryObject.setParameter(0, value);
		@SuppressWarnings("unchecked")
		List<User> results = queryObject.list();

		return results;

	}

	public List<User> findByFutureDays(String inputDate, Integer days,
			int begin, int length) {
		Session session = HibernateSessionFactory.getSession();
		String queryString = "from User where (TO_DAYS('" + inputDate
				+ "')-TO_DAYS(regTime))=" + days + " order by id desc";
		Query queryObject = session.createQuery(queryString);

		queryObject.setFirstResult(begin);
		queryObject.setMaxResults(length);
		@SuppressWarnings("unchecked")
		List<User> results = queryObject.list();

		return results;

	}

	public List<User> findByProperty(String propertyName, Object value,
			int begin, int length) {
		Session session = HibernateSessionFactory.getSession();
		String queryString = "from User as model where model." + propertyName
				+ "= ? order by id desc";
		Query queryObject = session.createQuery(queryString);
		queryObject.setParameter(0, value);
		queryObject.setFirstResult(begin);
		queryObject.setMaxResults(length);
		@SuppressWarnings("unchecked")
		List<User> results = queryObject.list();

		return results;

	}

	public User findByUserName(String uname) {
		Session session = HibernateSessionFactory.getSession();
		User instance = null;
		String queryString = "from User as model where model.userName= ?";
		Query queryObject = session.createQuery(queryString);
		queryObject.setParameter(0, uname);
		@SuppressWarnings("rawtypes")
		List results = queryObject.list();
		if (results != null && results.size() == 1)
			instance = (User) results.get(0);

		return instance;

	}

	public long findSizeByProperty(String propertyName, Object value) {
		Session session = HibernateSessionFactory.getSession();
		String queryString = "select count(*) from User as model where model."
				+ propertyName + "= ?";
		Query queryObject = session.createQuery(queryString);
		queryObject.setParameter(0, value);

		Object results = queryObject.uniqueResult();

		return results == null ? 0 : ((Number) results).longValue();

	}

	public List<User> searchByProperty(String propertyName, String value,
			int begin, int length) {

		Session session = HibernateSessionFactory.getSession();
		String queryString = "from User where " + propertyName + " like '%"
				+ value + "%'";
		Query queryObject = session.createQuery(queryString);
		queryObject.setFirstResult(begin);
		queryObject.setMaxResults(length);
		@SuppressWarnings("unchecked")
		List<User> results = queryObject.list();

		return results;

	}

	public List<User> searchByPropertyBySort(String propertyName, String value,
			int begin, int length, String sort) {

		Session session = HibernateSessionFactory.getSession();
		String queryString = "from User where " + propertyName + " like '%"
				+ value + "%' order by " + sort + " desc";
		Query queryObject = session.createQuery(queryString);
		queryObject.setFirstResult(begin);
		queryObject.setMaxResults(length);
		@SuppressWarnings("unchecked")
		List<User> results = queryObject.list();

		return results;

	}

	public long searchSizeByProperty(String propertyName, String value) {

		Session session = HibernateSessionFactory.getSession();
		String queryString = "select count(*) from User where " + propertyName
				+ " like '%" + value + "%'";
		Query queryObject = session.createQuery(queryString);
		Object results = queryObject.uniqueResult();

		return (results == null) ? 0 : ((Number) results).longValue();

	}

	public long verify(String uname, String pwd) {
		Session session = HibernateSessionFactory.getSession();
		String queryString = "from User as model where model.userName= ? and pwd=? ";
		Query queryObject = session.createQuery(queryString);
		queryObject.setParameter(0, uname);
		queryObject.setParameter(1, pwd);
		@SuppressWarnings("rawtypes")
		List results = queryObject.list();

		if (results != null && results.size() == 1)
			return 1;
		else
			return 0;

	}

}